﻿using famails.App_Code.source.bus;
using famails.App_Code.source.dto;
using famails.bus;
using famails.common;
using famails.dto;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Script.Services;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace famails.BackEnd.Customer
{
    public partial class CustomerCareAuto : System.Web.UI.Page
    {
        MailConfigBUS mailConfigBus = null;
        CM_CustomerCareAutoBUS Bus = null;
        SignatureBUS signBus = null;
        static UserLoginDTO userLogin = null;
        DataTable SignIn = null;
        protected void Page_Load(object sender, EventArgs e)
        {
            userLogin = getUserLogin();
            if (IsPostBack)
                ClientScript.RegisterHiddenField("isPostBack", "1");
            if (!IsPostBack)
            {
                try
                {
                    Bus = new CM_CustomerCareAutoBUS();
                    LoadCustomerGroupLists();
                    LoadSignatureList();
                    LoadContentList();
                    Session["listContentSend"] = null;
                    hdfCustomerCareAutoId.Value = Request.QueryString["id"] + "";
                    LoadCustomerCareAutoList();
                    LoadMailConfigList();
                    // Khoi tao session for store contentSendCustomerCareAuto
                    if (Session["listContentSend"] == null)
                    {
                        CM_CustomerCareAuto_Content_BUS cseBus = new CM_CustomerCareAuto_Content_BUS();
                        Session["listContentSend"] = cseBus.GetByCustomerCareAutoId(0, userLogin.UserId);
                    }
                    //ddlCustomerGroup.Enabled = Request.QueryString["id"] + "" == "";
                    //ddlProductGroup.Enabled = Request.QueryString["id"] + "" == "";
                }
                catch (Exception ex)
                {
                    Common.logs(userLogin.Username + "-Create-CustomerCareAuto - Page_Load", ex, Common.logType.error);
                    pnError.Visible = true;
                    lblError.Text = ex.Message;
                }

            }
        }

        private void LoadContentList()
        {
            try
            {
                SendContentBUS scBus = new SendContentBUS();
                DataTable dtContent = scBus.GetAllSendContent(getUserLogin().UserId, Common.contentType.AutoResponder);
                DataRow row = dtContent.NewRow();
                row["Subject"] = "Chọn nội dung";
                row["Id"] = "-1";
                dtContent.Rows.InsertAt(row, 0);
                if (dtContent.Rows.Count > 0)
                {

                    drlContent.DataSource = dtContent;
                    drlContent.DataTextField = "Subject";
                    drlContent.DataValueField = "Id";
                    drlContent.DataBind();
                }
            }
            catch (Exception ex)
            {
                Common.logs(userLogin.Username + "-Create-CustomerCareAuto - LoadContentList", ex, Common.logType.error);
            }
        }

        private void createTableSign()
        {
            SignIn = new DataTable("SignIn");
            DataColumn Id = new DataColumn("Id");
            Id.DataType = System.Type.GetType("System.Int32");
            DataColumn SignatureName = new DataColumn("SignatureName");
            DataColumn[] key = { Id };
            SignIn.Columns.Add(Id);
            SignIn.Columns.Add(SignatureName);
            SignIn.PrimaryKey = key;
        }
        private void LoadSignatureList()
        {
            try
            {

                signBus = new SignatureBUS();
                UserLoginDTO userLogin = getUserLogin();
                DataTable tblSignList = signBus.GetByUserId(userLogin.UserId);
                createTableSign();
                if (tblSignList.Rows.Count > 0)
                {
                    DataRow rowE = SignIn.NewRow();
                    rowE["Id"] = 0;
                    rowE["SignatureName"] = "Chọn chữ ký";
                    SignIn.Rows.Add(rowE);
                    foreach (DataRow RowItem in tblSignList.Rows)
                    {
                        rowE = SignIn.NewRow();
                        rowE["Id"] = RowItem["id"];
                        rowE["SignatureName"] = RowItem["SignatureName"];
                        SignIn.Rows.Add(rowE);
                    }
                    drlSign.DataSource = SignIn;
                    drlSign.DataTextField = "SignatureName";
                    drlSign.DataValueField = "id";
                    drlSign.DataBind();
                }
            }
            catch (Exception)
            {
            }
        }
        private void LoadContentSendCustomerCareAutoList(DataTable dataTable)
        {
            try
            {
                if (dataTable.Rows.Count > -1)
                {
                    dataTable.DefaultView.Sort = "orderno";
                    dataTable = dataTable.DefaultView.ToTable();
                    dlContentSendCustomerCareAuto.DataSource = dataTable;
                    dlContentSendCustomerCareAuto.DataBind();
                    for (int i = 0; i < dataTable.Rows.Count; i++)
                    {
                        Label lblNo = (Label)dlContentSendCustomerCareAuto.Items[i].FindControl("lblNo");
                        lblNo.Text = dataTable.Rows[i]["orderno"].ToString(); ; (i + 1).ToString();

                        Label lbtContent = (Label)dlContentSendCustomerCareAuto.Items[i].FindControl("lbtContent");
                        lbtContent.Text = dataTable.Rows[i]["Subject"].ToString();
                        Label lblHour = (Label)dlContentSendCustomerCareAuto.Items[i].FindControl("lblHour");
                        lblHour.Text = dataTable.Rows[i]["HourSend"].ToString() + " Giờ sau";

                        string id = dataTable.Rows[i]["Id"].ToString();
                        LinkButton lbtDelete = (LinkButton)dlContentSendCustomerCareAuto.Items[i].FindControl("lbtContentDelete");
                        lbtDelete.CommandArgument = id;

                    }
                }
            }
            catch (Exception ex)
            {
                Common.logs(userLogin.Username + "-Create-CustomerCareAuto - LoadContentSendCustomerCareAutoList", ex, Common.logType.error);
            }

        }

        private UserLoginDTO getUserLogin()
        {
            if (Session["us-login"] != null)
            {
                return (UserLoginDTO)Session["us-login"];
            }
            else Response.Redirect("~");
            return null;
        }
        protected void lbtInsertSignature_Click(object sender, EventArgs e)
        {
            try
            {
                int signId = int.Parse(((LinkButton)sender).CommandArgument.ToString());
                signBus = new SignatureBUS();
                DataTable tblSign = signBus.GetById(signId);
                if (tblSign.Rows.Count > 0)
                {
                    txtBody.Text = txtBody.Text + "\n" + tblSign.Rows[0]["SignatureContent"].ToString();
                }
            }
            catch (Exception ex)
            {

                Common.logs(userLogin.Username + "-Create-CustomerCareAuto - lbtInsertSignature_Click", ex, Common.logType.error);
            }

        }

        private void LoadCustomerCareAutoList()
        {
            try
            {
                string CustomerCareAutoId = this.hdfCustomerCareAutoId.Value;
                int ID = 0;
                if (CustomerCareAutoId != "")
                {
                    ID = int.Parse(CustomerCareAutoId);
                    DataTable dtCustomerCareAuto = Bus.GetByID(ID, userLogin.UserId);
                    if (dtCustomerCareAuto.Rows.Count > 0)
                    {

                        txtAutoName.Text = dtCustomerCareAuto.Rows[0]["Subject"].ToString();
                        drlMailConfig.SelectedValue = dtCustomerCareAuto.Rows[0]["ConfigId"].ToString();
                        ddlCustomerGroup.SelectedValue = dtCustomerCareAuto.Rows[0]["CustomerGroupId"]+"";
                        ddlProductList.SelectedValue = dtCustomerCareAuto.Rows[0]["ProductGroupId"].ToString();
                        // Hien thi ConentSendCustomerCareAuto list.
                        CM_CustomerCareAuto_Content_BUS cseBus = new CM_CustomerCareAuto_Content_BUS();
                        DataTable tblContent = cseBus.GetByCustomerCareAutoId(ID, userLogin.UserId);
                        if (tblContent.Rows.Count > 0)
                        {
                            Session["listContentSend"] = tblContent;
                            LoadContentSendCustomerCareAutoList(tblContent);
                        }

                    }
                }
            }
            catch (Exception ex)
            {

                Common.logs(userLogin.Username + "-Create-CustomerCareAuto - LoadCustomerCareAutoList", ex, Common.logType.error);
            }

        }

        private void LoadMailConfigList()
        {
            try
            {
                mailConfigBus = new MailConfigBUS();
                DataTable dtMailConfig = new DataTable();
                UserLoginDTO userLogin = getUserLogin();
                if (userLogin.DepartmentId == 1)
                {
                    dtMailConfig = mailConfigBus.GetAll();
                }
                else
                {
                    dtMailConfig = mailConfigBus.GetByUserId(userLogin.UserId);
                }
                drlMailConfig.Items.Clear();
                drlMailConfig.DataSource = dtMailConfig.DefaultView;
                drlMailConfig.DataTextField = "Email";
                drlMailConfig.DataValueField = "Id";
                drlMailConfig.DataBind();
            }
            catch (Exception ex)
            {

                Common.logs(userLogin.Username + "-Create-CustomerCareAuto - LoadMailConfigList", ex, Common.logType.error);
            }
        }

        private void LoadCustomerGroupLists()
        {
            try
            {
                CM_GroupBUS ulBus = new CM_GroupBUS();
                DataTable table = ulBus.GetAll2Order(getUserLogin().UserId);
                DataRow row = table.NewRow();
                row["GroupID"] = "-200";
                row["GroupName"] = "Chọn nhóm khách hàng";
                table.Rows.InsertAt(row, 0);
                row = table.NewRow();
                row["GroupID"] = "-100";
                row["GroupName"] = "Tất cả";
                table.Rows.InsertAt(row, 1);

                ddlCustomerGroup.DataTextField = "GroupName";
                ddlCustomerGroup.DataValueField = "GroupID";

                ddlCustomerGroup.DataSource = table;
                ddlCustomerGroup.DataBind();

                CM_ProductGroupBUS pglBus = new CM_ProductGroupBUS();
                table = pglBus.GetAll(getUserLogin().UserId);
               row = table.NewRow();
                row["ProductGroupID"] = "-200";
                row["ProductGroupName"] = "Chọn nhóm khách hàng";
                table.Rows.InsertAt(row, 0);
                row = table.NewRow();
                row["ProductGroupID"] = "-100";
                row["ProductGroupName"] = "Tất cả";
                table.Rows.InsertAt(row, 1);

                ddlProductList.DataTextField = "ProductGroupName";
                ddlProductList.DataValueField = "ProductGroupID";

                ddlProductList.DataSource = table;
                ddlProductList.DataBind();
            }
            catch (Exception ex)
            {

                Common.logs(userLogin.Username + "-Create-CustomerCareAuto - LoadCustomerGroupLists", ex, Common.logType.error);
            }
        }

        protected void btnSaveContentAndCustomerCareAuto_Click(object sender, EventArgs e)
        {
            try
            {
                Bus = new CM_CustomerCareAutoBUS();
                String CustomerCareAutoId = hdfCustomerCareAutoId.Value.ToString();
                CM_CustomerCareAutoDTO dto = new CM_CustomerCareAutoDTO();
                if (checkData() != "")
                {
                    pnSuccess.Visible = false;
                    pnError.Visible = true;
                    lblError.Text = checkData();
                    return;
                }
                int id = 0;
                int.TryParse(CustomerCareAutoId, out id); dto.CustomerCareAutoID = id;
                dto.ConfigId = Convert.ToInt32(drlMailConfig.SelectedValue);
                dto.Subject = txtAutoName.Text;
                dto.UserId = userLogin.UserId;
                dto.ProductGroupId = Convert.ToInt32(ddlProductList.SelectedValue);
                dto.CustomerGroupId = Convert.ToInt32(ddlCustomerGroup.SelectedValue);
                dto.IsStop = cbIsStop.Checked;

                int status = 1;// insert
                if (CustomerCareAutoId == "" || CustomerCareAutoId == null)//insert new
                {
                    int eId = Bus.Add(dto);
                    dto.CustomerCareAutoID = eId;
                    hdfCustomerCareAutoId.Value = eId.ToString();
                    Common.logs(userLogin.Username + " create CustomerCareAuto(" + eId + ")", null, Common.logType.info);

                }
                else //update
                {
                    status = 2;
                    dto.CustomerCareAutoID = int.Parse(CustomerCareAutoId);
                    Bus.Edit(dto);

                }
                // Store for ContentSendCustomerCareAuto table.
                saveContentSendCustomerCareAuto(dto.CustomerCareAutoID);
                CM_CustomerCareAutoBUS bus = new CM_CustomerCareAutoBUS();
                bus.addSendMailFromCustomerCareAuto(dto.CustomerCareAutoID, userLogin.UserId);
                LoadCustomerCareAutoList();
                pnSuccess.Visible = true;

                if (status == 1)
                {
                    lblSuccess.Text = "Bạn vừa thêm thành công sự kiện !";
                }
                else
                {
                    lblSuccess.Text = "Thông tin của sự kiện đã được cập nhật !";
                }
                //txtSubject.Text = txtBody.Text = txtAutoName.Text = "";
                //Session["listContentSend"] = null;
                pnError.Visible = false;
                // LoadCustomerCareAutoList();
            }
            catch (Exception ex)
            {
                Common.logs(userLogin.Username + "Create-CustomerCareAuto - btnSaveCustomerCareAuto_Click", ex, Common.logType.error);
                pnError.Visible = true;
                lblError.Text = ex.Message;
            }

        }
        private string checkData()
        {
            string msg = "";
            if (txtAutoName.Text == "")
            {
                msg = "Vui lòng nhập vào tiêu đề cho sự kiện !";
            }

            int c_group = 0;
            int p_group = 0;
            int.TryParse(ddlCustomerGroup.SelectedValue, out c_group);
            int.TryParse(ddlProductList.SelectedValue, out p_group);
            if (c_group == -200 && p_group == -200)
                msg = "Vui lòng chọn nhóm sản phẩm hoặc nhóm khách hàng!";
            if (c_group != -200 && p_group != -200)
                msg = "Chỉ được chọn nhóm sản phẩm hoặc nhóm khách hàng!";
            return msg;
        }
        protected void btnCreateNew_Click(object sender, EventArgs e)
        {
            try
            {
                resetForm();
                hdfCustomerCareAutoId.Value = "";
                Response.Redirect(Request.RawUrl);

                // Set null value for listContentSend session.
                CM_CustomerCareAuto_Content_BUS cseBus = new CM_CustomerCareAuto_Content_BUS();
                Session["listContentSend"] = cseBus.GetByCustomerCareAutoId(0, 0);

            }
            catch (Exception ex)
            {
                Common.logs(userLogin.Username + "Create-CustomerCareAuto - btnCreateNew_Click", ex, Common.logType.error);
                pnError.Visible = true;
                lblError.Text = ex.Message;
            }

        }
        protected void resetForm()
        {
            txtSubject.Text = "";
            txtBody.Text = "";
            drlMailConfig.SelectedIndex = 0;
            ddlCustomerGroup.SelectedIndex = 0;
            p_groupid.Value = "0";
        }
        protected DateTime convertStringToDate(string strDate)
        {
            int month = int.Parse(strDate.Substring(0, 2));
            int day = int.Parse(strDate.Substring(3, 2));
            int year = int.Parse(strDate.Substring(6, 4));
            int hours = int.Parse(strDate.Substring(11, 2));
            int minute = int.Parse(strDate.Substring(14, 2));
            DateTime dDate = new DateTime(year, month, day, hours, minute, 00);
            return dDate;
        }
        protected String convertDateToString(DateTime date)
        {
            int month = date.Month;
            int day = date.Day;
            int year = date.Year;
            int hours = date.Hour;
            int minute = date.Minute;
            String strDate = (month < 10) ? "0" + month : month + "";
            strDate += "/";
            strDate += (day < 10) ? "0" + day : day + "";
            strDate += "/";
            strDate += year + " ";
            strDate += (hours < 10) ? "0" + hours : hours + "";
            strDate += ":";
            strDate += (minute < 10) ? "0" + minute : minute + "";
            return strDate;

        }


        protected void lbtEdit_Click(object sender, EventArgs e)
        {
            try
            {
                visibleMessage(false);
                int CustomerCareAutoId = int.Parse(((LinkButton)sender).CommandArgument.ToString());
                DataTable dtCustomerCareAuto = Bus.GetByID(CustomerCareAutoId, userLogin.UserId);
                if (dtCustomerCareAuto.Rows.Count > 0)
                {
                    DataRow row = dtCustomerCareAuto.Rows[0];
                    hdfCustomerCareAutoId.Value = row["CustomerCareAutoId"].ToString();
                    txtSubject.Text = row["Subject"].ToString();
                    drlMailConfig.SelectedValue = row["ConfigId"].ToString();
                    ddlCustomerGroup.SelectedValue = row["CustomerGroupId"].ToString();
                    p_groupid.Value = row["ProductGroupId"].ToString();
                    txtBody.Text = row["Body"].ToString();

                }

                // Hien thi ConentSendCustomerCareAuto list.
                CM_CustomerCareAuto_Content_BUS cseBus = new CM_CustomerCareAuto_Content_BUS();
                DataTable tblContent = cseBus.GetByCustomerCareAutoId(CustomerCareAutoId, userLogin.UserId);
                if (tblContent.Rows.Count > 0)
                {
                    Session["listContentSend"] = tblContent;
                    LoadContentSendCustomerCareAutoList(tblContent);
                }

            }
            catch (Exception ex)
            {
                Common.logs(userLogin.Username + "Create-CustomerCareAuto - lbtEdit_Click", ex, Common.logType.error);
                pnError.Visible = true;
                lblError.Text = ex.Message;
            }

        }
        protected void visibleMessage(bool vis)
        {
            pnError.Visible = vis;
            pnSuccess.Visible = vis;
        }
        protected void btnSaveContent_Click(object sender, EventArgs e)
        {
            pnError.Visible = pnSuccess.Visible = false;
            SendContentBUS scBus = new SendContentBUS();
            if (txtSubject.Text.Trim() == "") { PanelHourError.Visible = true; lblHourError.Text = "Vui lòng nhập tiêu đề"; return; }
            if (txtBody.Text.Trim() == "") { PanelHourError.Visible = true; lblHourError.Text = "Vui lòng nhập nội dung"; return; }
            int temp = 0;
            if (int.TryParse(txtHour.Text, out temp) && temp < 0) { PanelHourError.Visible = true; lblHourError.Text = "Nhập sai giá trị giờ"; return; }
            if (int.TryParse(txtOrderNo.Text, out temp) && temp < 0) { PanelHourError.Visible = true; lblHourError.Text = "Nhập sai thứ tự gửi"; return; }
            try
            {
                PanelHourError.Visible = false;
                pnSuccess.Visible = false;

                int hour = int.Parse(txtHour.Text);
                int orderno = int.Parse(txtOrderNo.Text);
                DataTable dtContent = (DataTable)Session["listContentSend"];

                if (hdfContentIdEdit.Value + "" == "" && hour == 0 && dtContent != null && dtContent.Select("hoursend=" + hour).Length != 0) { PanelHourError.Visible = true; lblHourError.Text = "Trùng giá trị giờ!"; return; }

                int contentId = int.Parse(drlContent.SelectedValue);
                string contentSubject = drlContent.SelectedItem.ToString();
                string subject = this.txtSubject.Text;
                string body = this.txtBody.Text;
                if (hdfContentIdEdit.Value != "")
                {
                    DataRow[] rows = dtContent.Select("id=" + hdfContentIdEdit.Value);
                    if (rows.Length > 0)
                    {
                        rows[0]["subject"] = txtSubject.Text;
                        rows[0]["body"] = txtBody.Text;
                        rows[0]["hoursend"] = txtHour.Text;
                        rows[0]["orderno"] = txtOrderNo.Text;
                        if (txtHour.Text.Trim() == "0")
                            rows[0]["orderno"] = 0;
                        if (drlContent.SelectedValue + "" != "")
                            rows[0]["contentid"] = drlContent.SelectedValue;
                        hdfContentIdEdit.Value = "";
                        adhjskd.InnerText = "Thêm";
                        //txtHour.Enabled = true;

                        txtHour.Text = txtSubject.Text = txtBody.Text = "";

                    }
                }
                else
                {
                    DataRow row = dtContent.NewRow();
                    row["ContentId"] = contentId;
                    row["HourSend"] = hour;
                    row["OrderNo"] = orderno;
                    if (txtHour.Text.Trim() == "0")
                        row["orderno"] = 0;
                    row["Id"] = DateTime.Now.Millisecond;
                    row["subject"] = subject;
                    row["body"] = body;
                    dtContent.Rows.Add(row);
                }

                PanelHourError.Visible = false;
                pnSuccess.Visible = true;
                lblSuccess.Text = "Để hoàn thành cập nhật, bạn bấm 'Lưu sự kiện'.";

                LoadContentSendCustomerCareAutoList(dtContent);
                Session["listContentSend"] = dtContent;
                drlContent.SelectedIndex = 0;

            }
            catch (Exception ex)
            {
                Common.logs(userLogin.Username + "Create-CustomerCareAuto - btnSaveContent_Click", ex, Common.logType.error);
                PanelHourError.Visible = true;
                lblHourError.Text = "Nhập sai giá trị giờ !";
            }
        }
        protected void lbtContentDelete_Click(object sender, EventArgs e)
        {
            try
            {
                pnError.Visible = pnSuccess.Visible = false;
                CM_CustomerCareAuto_Content_BUS cseBus = new CM_CustomerCareAuto_Content_BUS();
                int contentId = int.Parse(((LinkButton)sender).CommandArgument.ToString());
                DataTable dtContent = (DataTable)Session["listContentSend"];
                if (dtContent.Rows.Count > 0)
                {
                    for (int i = 0; i < dtContent.Rows.Count; i++)
                    {
                        DataRow row = dtContent.Rows[i];
                        if (row["Id"].Equals(contentId))
                        {
                            // Xóa trong db, nếu có tồn tại.
                            if (hdfCustomerCareAutoId.Value != null)
                            {
                                //if (cseBus.CheckContentSent(contentId))
                                //{
                                cseBus.Delete(contentId); dtContent.Rows.Remove(row);
                                //}
                                //else
                                //{
                                //    PanelHourError.Visible = true;
                                //    lblHourError.Text = "Nội dung này đã được gửi thư, bạn không thể xóa!";
                                //}
                            }
                            else
                                dtContent.Rows.Remove(row);

                        }
                    }
                }
                LoadContentSendCustomerCareAutoList(dtContent);
            }
            catch (Exception ex)
            {
                Common.logs(userLogin.Username + "Create-CustomerCareAuto - btnDeleteContent_Click", ex, Common.logType.error);
            }

        }

        protected void saveContentSendCustomerCareAuto(int CustomerCareAutoId)
        {
            try
            {
                CM_CustomerCareAuto_Content_BUS cseBus = new CM_CustomerCareAuto_Content_BUS();
                DataTable dtContent = (DataTable)Session["listContentSend"];
                if (dtContent.Rows.Count > 0)
                {
                    for (int i = 0; i < dtContent.Rows.Count; i++)
                    {
                        DataRow row = dtContent.Rows[i];
                        CM_CustomerCareAuto_ContentDTO cseDto = new CM_CustomerCareAuto_ContentDTO();
                        cseDto.Id = int.Parse(row["Id"].ToString());
                        cseDto.CustomerCareAutoId = CustomerCareAutoId;
                        cseDto.ContentId = int.Parse(row["ContentId"].ToString());
                        cseDto.HourSend = int.Parse(row["HourSend"].ToString());
                        cseDto.OrderNo = int.Parse(row["OrderNo"].ToString());
                        cseDto.Subject = row["Subject"] + "";
                        cseDto.Body = row["Body"] + "";

                        int rsUpdate = cseBus.Edit(cseDto);
                        if (rsUpdate <= 0)
                        {
                            int id = cseBus.Add(cseDto);
                            dtContent.Rows[i]["id"] = id;
                            //SendContentDTO scDTO = new SendContentDTO();
                            //scDTO = getContentDTO();
                            //int contentID = new SendContentBUS().tblSendContent_insert(scDTO);
                        }
                    }
                    Session["listContentSend"] = dtContent;
                }
            }
            catch (Exception ex)
            {
                Common.logs(userLogin.Username + "Create-CustomerCareAuto - btnSaveContent_Click", ex, Common.logType.error);
            }
        }

        private SendContentDTO getContentDTO()
        {
            SendContentDTO scDTO = new SendContentDTO();
            scDTO.Body = txtBody.Text;
            scDTO.Subject = txtSubject.Text;
            scDTO.CreateDate = DateTime.Now;
            scDTO.userId = getUserLogin().UserId;

            return scDTO;
        }
        protected void lbtContentRefresh_Click(object sender, EventArgs e)
        {
            LoadContentList();
        }
        [System.Web.Services.WebMethod]
        public static string Spam(string content)
        {
            try
            {
                string[] _content = Regex.Split(content, "//Hung-Hai//");
                SpamRuleBUS spamBUS = new SpamRuleBUS();
                DataTable spam = spamBUS.GetAll();
                float totalScoreTitle = 0;
                float totalScoreContent = 0;
                string ruleContent = "";
                float ItemScore = 0;
                string key = "";
                string titleData = _content[0];
                string contentData = _content[1];
                #region MyRegion
                #region Fisrt
                ruleContent = "<div class='toolTipBox' style='padding: 5px; margin-top: 10px; background-color: rgb(224, 236, 255);" +
                        "color: rgb(51, 51, 51); text-decoration: none; margin-bottom: 15px; font-family: Tahoma, Arial;" +
                        "font-size: 11px; font-style: normal; font-variant: normal; font-weight: normal;" +
                        "letter-spacing: normal; line-height: normal; orphans: auto; text-align: start;" +
                        "text-indent: 0px; text-transform: none; white-space: normal; widows: auto; word-spacing: 0px;" +
                        "-webkit-text-stroke-width: 0px;'>" +
                        "<img align='left' height='16' src='../resource/images/infoballon.gif' width='20' />Thống" +
                        "kê nội dung các quy tắc vi phạm của &#39;<b>Tiêu đề gửi</b>&#39; chi tiết như bên" +
                        " dưới:</div>" +
                        "<div class='Heading2' style='font-weight: bold; color: rgb(0, 0, 0); height: 16pt;" +
                        "background-color: rgb(237, 236, 236); padding: 4px 4px 4px 10px; background-image: url(../resource/images/table_bg.gif);" +
                        "font-family: Tahoma, Arial; font-size: 11px; font-style: normal; font-variant: normal;" +
                        "letter-spacing: normal; line-height: normal; orphans: auto; text-align: start;" +
                        "text-indent: 0px; text-transform: none; white-space: normal; widows: auto; word-spacing: 0px;" +
                        "-webkit-text-stroke-width: 0px;'>" +
                        "<div class='spamRuleBroken_row_rulename' style='float: left; padding: 3px 0px 3px 5px;'>" +
                        "Quy tắc vi phạm</div>" +
                        "<div class='spamRuleBroken_row_rulescore' style='float: right; width: 80px; text-align: right;" +
                        "padding: 3px 15px 3px 5px;'>" +
                        "Điểm</div>" +
                        "&nbsp;</div>" +
                        "<div class='spam_info spamRuleBroken_row' style='padding: 4px 8px; background-color: rgb(249, 249, 249);" +
                       " display: block; clear: both; color: rgb(103, 103, 103); font-family: Tahoma, Arial;" +
                        "font-size: 11px; font-style: normal; font-variant: normal; font-weight: normal;" +
                        "letter-spacing: normal; line-height: normal; orphans: auto; text-align: start;" +
                        "text-indent: 0px; text-transform: none; white-space: normal; widows: auto; word-spacing: 0px;" +
                        "-webkit-text-stroke-width: 0px;'>";
                #endregion Fisrt
                foreach (DataRow RowItem in spam.Rows)
                {
                    key = " " + RowItem["Keyword"].ToString() + " ";
                    ItemScore = float.Parse(RowItem["Score"].ToString());
                    if (titleData.Contains(key) == true)
                    {
                        //Bắt đầu vòng lặp tính điểm tiêu đề
                        ruleContent += "<div class='spam_info spamRuleBroken_row' style='padding: 4px 8px; background-color: rgb(249, 249, 249);" +
                              "display: block; clear: both; color: rgb(103, 103, 103); font-family: Tahoma, Arial;" +
                              "font-size: 11px; font-style: normal; font-variant: normal; font-weight: normal;" +
                              "letter-spacing: normal; line-height: normal; orphans: auto; text-align: start;" +
                              "text-indent: 0px; text-transform: none; white-space: normal; widows: auto; word-spacing: 0px;" +
                              "-webkit-text-stroke-width: 0px;'>";
                        ruleContent += "<div class='spamRuleBroken_row_rulename' style='float: left; padding: 3px 0px 3px 5px;'>" + "Chứa từ vi phạm '" + key + "'" + "</div>" +
                         "<div class='spamRuleBroken_row_rulescore' style='float: right; width: 80px; text-align: right;" + "padding: 3px 15px 3px 5px;'>" + ItemScore + "</div> </br>";
                        ruleContent += "</div>";
                        totalScoreTitle = totalScoreTitle + ItemScore;
                        // Kết thúc vòng lặp tính điểm tiêu đề
                    }
                }

                #region Medium
                ruleContent += "" +
                  "<div class='spam_info spamRuleBroken_row' style='padding: 4px 8px; background-color: rgb(249, 249, 249);" +
                   "display: block; clear: both; color: rgb(103, 103, 103); font-family: Tahoma, Arial;" +
                   "font-size: 11px; font-style: normal; font-variant: normal; font-weight: normal;" +
                   "letter-spacing: normal; line-height: normal; orphans: auto; text-align: start;" +
                   "text-indent: 0px; text-transform: none; white-space: normal; widows: auto; word-spacing: 0px;" +
                   "-webkit-text-stroke-width: 0px;'>" +
                   "<div class='spamRuleBroken_graph' style='border: 1px solid gray; height: 5px; background-color: rgb(238, 238, 238);'>" +
                   "<div class='spam_notspam' style='background-color: rgb(0, 255, 0); height: 5px; width: 165.296875px;'>" +
                   "<img height='5' src='../resource/images/1x1.gif' width='1' /></div>" +
                   "</div>" +
                   "<div style='line-height: 1; margin-bottom: 5px;'>" +
                   "<br />" +
                   "Nội dung được đánh giá cao nhất<span class ='Apple-converted-space'>&nbsp;</span><span" +
                   " style='font-size: 12px; font-weight: bold;'><b>" + totalScoreTitle.ToString() + "</b></span><span class='Apple-converted-space'>&nbsp;</span>trong" +
                   " ngưỡng cho phép là 5. Điều này có nghĩa email của bạn sẽ được gửi đến đích, nhưng" +
                   "điều này không được bảo đảm tuyệt đối nó chỉ có giá trị tham khảo.</div>" +
                "</div>" +
                "<div class='toolTipBox' style='padding: 5px; margin-top: 10px; background-color: rgb(224, 236, 255);" +
                "color: rgb(51, 51, 51); text-decoration: none; margin-bottom: 15px; font-family: Tahoma, Arial;" +
                "font-size: 11px; font-style: normal; font-variant: normal; font-weight: normal;" +
                "letter-spacing: normal; line-height: normal; orphans: auto; text-align: start;" +
                "text-indent: 0px; text-transform: none; white-space: normal; widows: auto; word-spacing: 0px;" +
                "-webkit-text-stroke-width: 0px;'>" +
                "<img align='left' height='16' src='../resource/images/infoballon.gif' width='20' />Thống" +
                " kê nội dung các quy tắc vi phạm của &#39;<b>Nội dung gửi</b>&#39; chi tiết như" +
                " bên dưới:" + "</div>" +
                 "<div class='Heading2' style='font-weight: bold; color: rgb(0, 0, 0); height: 16pt;" +
                 "background-color: rgb(237, 236, 236); padding: 4px 4px 4px 10px; background-image: url(../resource/images/table_bg.gif);" +
                 "font-family: Tahoma, Arial; font-size: 11px; font-style: normal; font-variant: normal;" +
                 "letter-spacing: normal; line-height: normal; orphans: auto; text-align: start;" +
                 "text-indent: 0px; text-transform: none; white-space: normal; widows: auto; word-spacing: 0px;" +
                 "-webkit-text-stroke-width: 0px;'>" +
                 "<div class='spamRuleBroken_row_rulename' style='float: left; padding: 3px 0px 3px 5px;'>" +
                 "Quy tắc vi phạm</div>" +
                 "<div class='spamRuleBroken_row_rulescore' style='float: right; width: 80px; text-align: right;" +
                 "padding: 3px 15px 3px 5px;'>" +
                 "Điểm</div>" +
                "&nbsp;</div>";

                #endregion
                //Đánh giá nội dung
                foreach (DataRow RowItem in spam.Rows)
                {
                    key = " " + RowItem["Keyword"].ToString() + " ";
                    ItemScore = float.Parse(RowItem["Score"].ToString());
                    if (contentData.Contains(key) == true)
                    {
                        //Bắt đầu vòng lặp tính điểm tiêu đề
                        ruleContent += "<div class='spam_info spamRuleBroken_row' style='padding: 4px 8px; background-color: rgb(249, 249, 249);" +
                                     "display: block; clear: both; color: rgb(103, 103, 103); font-family: Tahoma, Arial;" +
                                     "font-size: 11px; font-style: normal; font-variant: normal; font-weight: normal;" +
                                     "letter-spacing: normal; line-height: normal; orphans: auto; text-align: start;" +
                                     "text-indent: 0px; text-transform: none; white-space: normal; widows: auto; word-spacing: 0px;" +
                                     "-webkit-text-stroke-width: 0px;'>";
                        ruleContent += "<div class='spamRuleBroken_row_rulename' style='float: left; padding: 3px 0px 3px 5px;'>" + "Chứa từ vi phạm '" + key + "'" + "</div>" +
                         "<div class='spamRuleBroken_row_rulescore' style='float: right; width: 80px; text-align: right;" + "padding: 3px 15px 3px 5px;'>" + ItemScore + "</div></br>";
                        ruleContent += "</div>";
                        totalScoreContent = totalScoreContent + ItemScore;
                        // Kết thúc vòng lặp tính điểm tiêu đề
                    }
                }

                //Kết thúc đánh giá nội dung
                #region End
                ruleContent += "" +
                  "<div class='spam_info spamRuleBroken_row' style='padding: 4px 8px; background-color: rgb(249, 249, 249);" +
                  "display: block; clear: both; color: rgb(103, 103, 103); font-family: Tahoma, Arial;" +
                  "font-size: 11px; font-style: normal; font-variant: normal; font-weight: normal;" +
                  "letter-spacing: normal; line-height: normal; orphans: auto; text-align: start;" +
                  "text-indent: 0px; text-transform: none; white-space: normal; widows: auto; word-spacing: 0px;" +
                  "-webkit-text-stroke-width: 0px;'>" +
                  "<div class='spamRuleBroken_graph' style='border: 1px solid gray; height: 5px; background-color: rgb(238, 238, 238);'>" +
                  "<div class='spam_notspam' style='background-color: rgb(0, 255, 0); height: 5px; width: 50%;'>" +
                  "<img height='5' src='../../resource/images/1x1.gif' width='1' /></div>" + "</div>" +
                   "<div style='line-height: 1; margin-bottom: 5px;'>" + "<br />" +
                   "Nội dung được đánh giá cao nhất<span class='Apple-converted-space'>&nbsp;</span><span" +
                   " style='font-size: 13px; font-weight: bold;'>" + totalScoreContent.ToString() + "</span><span class='Apple-converted-space'>&nbsp;</span>trong" +
                   " ngưỡng cho phép là 5. Điều này có nghĩa email của bạn sẽ được gửi đến đích, nhưng" +
                   "điều này không được bảo đảm tuyệt đối nó chỉ có giá trị tham khảo." +
                    "</div>" +
                "</div>";
                #endregion
                #endregion
                return ruleContent;
            }
            catch (Exception)
            {
                return null;
            }

        }
        [System.Web.Services.WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static string contentUpdate(string content)
        {
            string con = content;
            return null;
        }
        protected void lbtEdit_Click1(object sender, EventArgs e)
        {
            pnError.Visible = pnSuccess.Visible = false;
            LinkButton button = (LinkButton)sender;
            DataTable dtContent = (DataTable)Session["listContentSend"];
            if (dtContent != null && dtContent.Rows.Count > 0)
            {
                DataRow[] rows = dtContent.Select("id=" + button.CommandArgument);
                if (rows.Length > 0)
                {
                    txtSubject.Text = rows[0]["subject"] + "";
                    txtBody.Text = rows[0]["body"] + "";
                    txtHour.Text = rows[0]["hoursend"] + "";
                    txtOrderNo.Text = rows[0]["orderno"] + "";
                    try
                    {
                        if (rows[0]["contentid"] + "" != "")
                            drlContent.Text = rows[0]["contentid"] + "";
                    }
                    catch { }
                    hdfContentIdEdit.Value = button.CommandArgument;
                    adhjskd.InnerHtml = "<span style='margin-right:10px;' class='fa fa-upload'></span>Cập nhật";
                    txtHour.Enabled = false;
                }
            }
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static List<CM_ProductGroupDTO> LoadTree()
        {
            List<CM_ProductGroupDTO> result = new List<CM_ProductGroupDTO>();

            CM_ProductGroupBUS bus = new CM_ProductGroupBUS();
            DataTable source = bus.GetProductGroup(userLogin.UserId, 1);
            CM_ProductGroupDTO item = new CM_ProductGroupDTO();
            item.ProductGroupID = -200;
            item.ProductGroupName = "Chọn nhóm sản phẩm";
            item.children = new List<CM_ProductGroupDTO>();
            result.Add(item);
            item = new CM_ProductGroupDTO();
            item.ProductGroupID = -100;
            item.ProductGroupName = "Tất cả";
            item.children = new List<CM_ProductGroupDTO>();
            result.Add(item);

            foreach (DataRow row in source.Rows)
            {
                CM_ProductGroupDTO dto = new CM_ProductGroupDTO();
                dto.ProductGroupName = row["ProductGroupName"] + "";
                dto.ProductGroupID = Convert.ToInt32(row["ProductGroupID"]);
                dto.CreateDate = Convert.ToDateTime(row["CreateDate"]);
                dto.children = GetChildGroup(dto.ProductGroupID, Convert.ToInt32(row["GroupStep"]) + 1);
                result.Add(dto);
            }

            return result;
        }
        static List<CM_ProductGroupDTO> GetChildGroup(int parentid, int groupstep)
        {
            CM_ProductGroupBUS bus = new CM_ProductGroupBUS();
            List<CM_ProductGroupDTO> result = new List<CM_ProductGroupDTO>();
            DataTable source = bus.GetChildGroup(parentid, groupstep, userLogin.UserId);
            foreach (DataRow row in source.Rows)
            {
                CM_ProductGroupDTO dto = new CM_ProductGroupDTO();
                dto.ProductGroupName = row["ProductGroupName"] + "";
                dto.ProductGroupID = Convert.ToInt32(row["ProductGroupID"]);
                dto.children = GetChildGroup(dto.ProductGroupID, Convert.ToInt32(row["GroupStep"]) + 1);
                result.Add(dto);
            }
            return result;
        }
    }
}